﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace Legend.Data
{
    public static class DataTableBuilderExtensions
    {
        public static DataTable DefineColumns(this DataTable table, params string[] columnNames)
        {
            Require.ThatArgument(table).Named("table").IsNotNull();
            Require.ThatArgument(columnNames).Named("columnNames").IsNotNull();

            if (table.Columns.Count > 0)
            {
                throw new InvalidOperationException("Columns can only be defined for tables that has no columns.");
            }

            foreach (var columnName in columnNames)
            {
                table.Columns.Add(columnName);
            }

            return table;
        }

        public static DataTable DefineColumns(this DataTable table, IDictionary<string, Type> columnNamesAndTypes)
        {
            Require.ThatArgument(table).Named("table").IsNotNull();
            Require.ThatArgument(columnNamesAndTypes).Named("columnNamesAndTypes").IsNotNull();

            foreach (var columnDefinition in columnNamesAndTypes)
            {
                table.Columns.Add(columnDefinition.Key, columnDefinition.Value);
            }

            return table;
        }

        public static DataTable DefineColumns(this DataTable table, string columnNames, char delimiter)
        {
            Require.ThatArgument(table).Named("table").IsNotNull();
            Require.ThatArgument(columnNames).Named("columnNames").IsNotNullOrEmpty();

            foreach (var name in columnNames.Split(delimiter))
            {
                table.Columns.Add(name.Trim());
            }

            return table;
        }

        public static DataRow AddRow(this DataTable table)
        {
            Require.ThatArgument(table).Named("table").IsNotNull();

            return table.Rows.Add();
        }

        public static DataRow SetValue<T>(this DataRow row, string columnName, T value)
        {
            Require.ThatArgument(row).Named("row").IsNotNull();
            Require.ThatArgument(columnName).Named("columnName").IsNotNull();

            row[columnName] = value;

            return row;
        }

        public static DataTable DoneWithRow(this DataRow row)
        {
            Require.ThatArgument(row).Named("row").IsNotNull();

            return row.Table;
        }
    }
}
